﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Clandestine.Conversations
{
    public abstract class ConversationPart
    {
        /// <summary>
        /// Gets the next part of the conversation, or null if this is the final conversation part. 
        /// (It's a property because QuestionPart will return a different next part depending on it's answer.)
        /// </summary>
        public virtual ConversationPart NextPart
        {
            get { return nextPart; }
            set { nextPart = value; }
        }
        protected ConversationPart nextPart;

        public DialogueWindow Window
        {
            get 
            {
                if (Conversation.DialogueWindows.ContainsKey(SpeakerName))
                    return Conversation.DialogueWindows[SpeakerName];
                else
                    throw new IndexOutOfRangeException("Could not find speaker with that name!");
            }
        }

        public string SpeakerName = string.Empty;
        public Conversation Conversation;

        public virtual void WaitForSelection()
        {
            // Setup the delegate.
            // I use an event and not use .IsPressed or whatever, as we want to make sure the key isn't held down
            // and multiple menu's dialogue screens fly by, effectively we wait for a KeyUp between screens.
            bool selection = false;
            KeyEventDelegate onKeyDown = new KeyEventDelegate(delegate (Key k) {
                if (k == Key.Select)
                    selection = true;
            });
            Keyboard.KeyDown += onKeyDown;

            // Loop until the above delegate is called.
            while (!selection)
                System.Threading.Thread.Sleep(100);
            Keyboard.KeyDown -= onKeyDown;
        }

        public abstract void Do();
        public abstract List<ConversationPart> ParseXML(XmlTextReader xml);
    }
}
